<template>
  <div class="cate_list">
    
    <!-- 面包屑 -->
    <el-header class="top">
      <i class="el-icon-s-home"></i>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/' }">分类管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-header>

    <!-- 搜索、列表、分页-->
    <el-card class="box-card">
        <div slot="header" class="clearfix">
            <span>分类管理</span>
            <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
        </div>
       
        <el-container class="main">
            <el-row class="search">
                <el-col :span="20">
                    <el-form :inline="true" class="demo-form-inline" :model="searchForm">
                        <el-form-item label="名称">
                            <el-input  placeholder="分类名称搜索" v-model="searchForm.title"></el-input>
                        </el-form-item>

                        <el-form-item label="状态">
                            <el-select placeholder="是否启用" v-model="searchForm.status">
                                <el-option label="启用" :value="0"></el-option>
                                <el-option label="禁用" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item>
                            <el-button type="primary">查询</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addCategory">添加</el-button>
                </el-col>
            </el-row>
            
            <el-row class="list">
                <el-col :span="24">
                    <el-table
                        :data="tableData"
                        style="width: 100%"
                    >
                        <el-table-column
                            prop="id"
                            label="ID"
                            width="180">
                        </el-table-column>

                        <el-table-column
                            prop="cate_name"
                            label="分类名"
                            max-width="180">
                        </el-table-column>

                        <el-table-column
                            prop="order_num"
                            label="排序">
                        </el-table-column>

                        <el-table-column
                            prop="is_show"
                            label="是否用">
                            <template slot-scope="scope">
                                {{ scope.row.is_show == 1 ? '启用' : '禁用' }}
                            </template>
                        </el-table-column>

                        <el-table-column  label="操作">
                            <!-- 自定义列模板 注意03：table-column使用自定义模板后，在table-column上的width、max-width属性无效.要
                                 写在 template 组件上
                            -->
                            <!-- #/admin/category/detail/2 -->
                            <template slot-scope="scope"  width="220">
                                <el-button size="mini">
                                    <router-link :to="'/admin/category/detail/'+scope.row.id"> 查看1</router-link>
                                </el-button>

                                <el-button size="mini" @click="showEditDialog(scope.row.id)">
                                   查看2
                                </el-button>

                                <el-button size="mini" type="warning"  @click="showEditDialog2(scope.row.id)">编辑</el-button>

                                <!-- <el-button
                                    size="mini"
                                    type="danger"
                                    @click="delCate(scope.row.id)"
                                >
                                    删除
                                </el-button> -->
                                <el-popconfirm
                                    title="确定删除此分类吗？"
                                    placement="top"
                                    @confirm="delCate(scope.row.id)"
                                    v-on:cancel="cancelDelCate"
                                    style="margin-left: 8px;"
                                    aria-hidden
                                >
                                    <el-button
                                        size="mini"
                                        type="danger"
                                        slot="reference"
                                    >
                                        删除
                                    </el-button>
                                    <!-- <el-button slot="reference">删除</el-button> -->

                                </el-popconfirm>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-col>
            </el-row>
        
            <el-row class="page_box">
                <el-col :span="24">
                    <!--   :hide-on-single-page="true" 只有1页的时候不显示分页条 -->
                    <el-pagination
                        layout="total, sizes, prev, pager, next, jumper"
                      
                        :page-sizes="pageSizes"
                        :page-size="pageSize"
                        :total="totalNum"
                        
                        @size-change="changeSize"
                        @current-change="changPage"
                    >
                         <!-- size-change pageSize 改变时会触发 -->
                    </el-pagination>

                </el-col>
            </el-row>
        </el-container>
    </el-card>

    <!-- 注意02：弹窗是跟主体内容的层级是并列关系，放最外面 -->
    <!-- 查看分类 -->
    <el-dialog
        title="查看分类"
        :visible.sync="dialogEdit"
        width="30%">

       <!-- 查看表单 -->
       <el-form ref="addForm" :model="ctgy" label-width="80px" :rules="formRules" >
            <el-form-item label="分类名" prop="cate_name">
                <el-input v-model="ctgy.cate_name" style="width:300px" placeholder="输入文章标题"></el-input>
            </el-form-item>

            <el-form-item label="排序" prop="order_num">
                <el-input v-model="ctgy.order_num" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="是否启用">
                <!-- 选项文字放el-radio标签中，label表示值 -->
                <el-radio-group v-model="ctgy.is_show">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
                <!-- {{ ctgy.is_show }} -->
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="hideEditDialog">取 消</el-button>
            <el-button type="primary" @click="hideEditDialog">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 添加分类 -->
    <el-dialog title="添加分类" :visible.sync="dialogFormVisible" width="30%">

        <el-form :model="ctgy" ref="addForm" :rules="formRules">
            <el-form-item label="分类名" prop="cate_name" :label-width="formLabelWidth">
              <el-input v-model="ctgy.cate_name" style="width:300px" placeholder="输入文章标题"></el-input>
            </el-form-item>

            <el-form-item label="排序" prop="order_num" :label-width="formLabelWidth">
              <el-input v-model="ctgy.order_num" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="是否启用" :label-width="formLabelWidth">
              <el-radio-group v-model="ctgy.is_show">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>

        </el-form>

        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit('addForm')">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 编辑分类 -->
    <el-dialog
        title="编辑分类"
        :visible.sync="dialogEdit2"
        width="30%">

       <!-- 查看表单 -->
       <el-form ref="addForm" :model="ctgy" label-width="80px" :rules="formRules" >
            <el-form-item label="分类名" prop="cate_name">
                <el-input v-model="ctgy.cate_name" style="width:300px" placeholder="输入文章标题"></el-input>
            </el-form-item>

            <el-form-item label="排序" prop="order_num">
                <el-input v-model="ctgy.order_num" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="是否启用">
                <!-- 选项文字放el-radio标签中，label表示值 -->
                <el-radio-group v-model="ctgy.is_show">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
                <!-- {{ ctgy.is_show }} -->
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="hideEditDialog2">取 消</el-button>
            <el-button type="primary" @click="saveCateEdit">保存修改</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import http from '../utils/http';

export default {
    data(){
        return {
            // 表格数据
            tableData: [
                // {
                //     "id": 9,
                //     "cate_name": "递归函数2",
                //     "order_num": 0,
                //     "is_show": 0
                // },
                // {
                //     "id": 2,
                //     "cate_name": "设计模式",
                //     "order_num": 0,
                //     "is_show": 1
                // },
                // {
                //     "id": 9,
                //     "cate_name": "递归函数2",
                //     "order_num": 0,
                //     "is_show": 0
                // },
                // {
                //     "id": 2,
                //     "cate_name": "设计模式",
                //     "order_num": 0,
                //     "is_show": 1
                // }
            ],

            // 分页相关参数
            pageSizes: [6, 20, 30, 40], //每页显示多少条数据的数组，用用户可以调整每页显示多少条数据
            // pageSizes: [2, 3, 4, 5],
            pageSize:6, //每页面显示多少条数据，它来自pageSizes 其中的一项
            totalNum:0, //总条数
            pageNum:1,  //当前页码，默认是1，也就是说默认显示第1页

            //查看的弹窗
            dialogEdit: false, // true显示，false隐藏
            
            //注意01：查看、添加、修改 共用的表单数据
            ctgy:{
                cate_name:"",
                order_num:"", //分类排序，从小到大排列，默认为0
                is_show:1,    // 1 启用、0 禁用
            },
            formLabelWidth: '120px',

             //验证规则
            formRules:{
                cate_name: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { min: 3, max: 30, message: '长度在 3 到30个字符', trigger: 'blur' }
                ],
                order_num: [
                    { required: true, message: '请输排序值', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 5位的数字', trigger: 'blur' }
                ]
            },

            // 添加弹窗
            dialogFormVisible: false,

            // 修改弹窗
            dialogEdit2:false,
            cid:0, //要修改的分类id

            // 搜索表单项目
            searchForm:{
                title:"",
                status:1
            }
        }
    },
    created(){
        this.getCateList(); //页面一进来的时候获取数据
    },
    methods:{
        async getCateList(){
            let res = await http.get(
                '/api/article/cate_list',
                {
                    //get请求其它配置，params就表示携带的参数
                    params:{
                        // 参数的名称、值
                        page_size:this.pageSize,
                        page:this.pageNum
                    }
                }
            )
            console.log(res)

            // 如果成功取数据了，就把后端取到的数据显示在模板中（给变量tableData）
            const ret = res.data||{}; //接口数据
            console.log(ret)

            if(ret.code == 0){
                this.tableData = ret.result; //保存列表
                this.totalNum = ret.total;   //总条数
            }
        },
        changeSize(pg_size){
            console.log('修改了每页显示的条数:'+pg_size)
            this.pageSize = pg_size;
            this.getCateList() //调整每页显示的条数后（page_size）后重新获取数据
        },
        changPage(page_num){
            console.log(`当前您点选择了第:${page_num}页`)
            this.pageNum = page_num; //保存，后面备
            this.getCateList() //调整页码后（page），取对应页码的数据
        },
        //查看
        async showEditDialog(cid){
            //显示对话框
            this.dialogEdit = true;
            //发请求获取数据
            console.log("分类的id是:"+cid)
            let res =await http.get("/api/article/cate_edit/"+cid)
            let result = res.data;
            
            //保存数据
            if(result.code == 0){
                let info = result.data;
                this.ctgy.cate_name = info.cate_name;
                this.ctgy.order_num = info.order_num;
                this.ctgy.is_show = info.is_show;
            }
        },
        hideEditDialog(){
            this.dialogEdit = false;
        },
        //添加
        addCategory(){
            this.dialogFormVisible = true;
        },
        // 修改
        async showEditDialog2(cid){
            //显示对话框
            this.dialogEdit2 = true;
            
            //保存一下当前修改的分类id,提交表单的时候用
            this.cid = cid;

            //发请求获取数据
            console.log("分类的id是:"+cid)
            let res =await http.get("/api/article/cate_edit/"+cid)
            let result = res.data;
            
            //保存数据
            if(result.code == 0){
                let info = result.data;

                this.ctgy.cate_name = info.cate_name;
                this.ctgy.order_num = info.order_num;
                this.ctgy.is_show = info.is_show;
            }
        },
        hideEditDialog2(){
            this.dialogEdit2 = false;
        },
        async saveCateEdit(){
            // 取数据
            // 保存
            let url = `/api/article/cate_save_edit/${this.cid}`
            let res = await http.post(url,{
                cate_name:this.ctgy.cate_name,
                order_num:this.ctgy.order_num,
                is_show:this.ctgy.is_show
            })
            let result = res.data;
            
            if(result.code == 0){
                // 成功
                this.$message({
                    type:"success",
                    message:result.msg
                })
                // 隐藏对话框
                this.dialogEdit2=false;
            }else{
                this.$message({
                    type:"warning",
                    message:result.msg
                })
            }
        },
        onSubmit(formName){
        console.log("提交表单")
        //  this.$refs[formName] 获取表单
        // this.$refs[formName].validate 调用表单验证方法，告诉我们验证是否通过
        this.$refs[formName].validate(async (valid)=>{
          console.log(valid) //true 通过
          
          // 通过,
          if(valid){
              // 1.axios请求后端，把数据发给别个，让别个保存起来
              let res = await http.post(
                "/api/article/cate_add",
                {
                  cate_name:this.ctgy.cate_name,
                  order_num:this.ctgy.order_num,
                  is_show:this.ctgy.is_show
                }
              )

              console.log(res,res.data)

              // 1.1 成功
              if(res.data.code == 0){
                // Message 消息提示
                this.$message({
                  type:"success",
                  message:"添加成功"
                })
                
                //重置表单
                this.resetForm();
                //隐藏弹窗
                this.dialogFormVisible = false;
              }else{
              // 1.2 不成功
                this.$message({
                  type:"error",
                  message:res.data.msg
                })
              }
          }else{
            // 没有通过验证，给用户一个提示
            this.$message({
              type:"warning",
              message:"请按要求，完整填写表单!"
            })
          }
        });
      },
      resetForm(){
        this.$refs.addForm.resetFields();
        //没有验证的表单元素不会被重置，哪我们就手动重置。
        this.ctgy.cate_name="";
        this.ctgy.order_num=0;
        this.ctgy.is_show=1
      },
     // 删除分类
     async delCate(cid){
        console.log("要删除的分类id:"+cid)
        // 向后端发请求，删除数据 /article/cate_delete/8  8 分类id
        let url = `/api/article/cate_delete/${cid}`
        let res = await http.get(url)
        console.log("del cate----->",res)

        // 得到结果
        let result = res.data||{}

        // 提示用户
        // 后端如返回了提示信息，则直接用后给的(msg)
        // this.$message({type:"success",message:result.msg})

        // 根据状态码(code)显示提示信息
        if(result.code == 0){
            this.$message({type:"success",message:result.msg})
        }else{
            this.$message({type:"success",message:result.msg})
        }
        
        // 刷新列表-调用获取列表数据的方法
        this.getCateList(); 
      },
      cancelDelCate(){
        this.$message({
            type:"info",
            message:"您已经取消了删除"
        })
      }
    }
}
</script>

<style lang="less" scoped>
    .cate_list{
        // /deep/ 深度选择器，可以重置组件内置的样式。别忘了样式要加scoped，
        // 有可能还需要!important来提升样式的优先级。
        /deep/.el-header {
            display: flex;
            align-items: center;
            height: 62px !important;
            background: #edebeb;

            .el-icon-s-home {
            color: #000000;
            font-size: 20px;
            }

            .el-breadcrumb {
            height: 35px;
            display: flex;
            align-items: center;
            margin-bottom: 0;
            font-size: 12px;
            }
        }

        // 搜索、列表
        .box-card{
            margin: 10px;

            .main{
                width: 100%;
                display: flex;
                flex-direction: column;
                
                // 搜索
                .search{
                    width: 100%;

                    .el-col{
                        &:last-child{
                            text-align: right;
                        }
                    }
                }
                
                // 列表
                .list{
                    clear:both;
                }

                // 分页
                .page_box{
                    margin-top: 15px;
                    text-align: center
                }

            }
        }
    }
</style>